package com.octopus.service.impl;

import java.util.HashMap;
import java.util.Map;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.alibaba.fastjson.JSONObject;
import com.octopus.conifg.WxConstantConfig;
import com.octopus.domain.AccessToken;
import com.octopus.service.TokenService;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.http.HttpUtil;
import lombok.extern.slf4j.Slf4j;

@Slf4j
@Service
public class TokenServiceImpl implements TokenService {
    @Autowired
    private WxConstantConfig wxConstantConfig;

    /**
     * 获取接口访问凭证
     *
     * @return 认证信息
     */
    @Override
    public AccessToken getAccessToken() {
        AccessToken accessToken = new AccessToken();
        Map<String, Object> paramMap = new HashMap<>();
        paramMap.put("grant_type", wxConstantConfig.getGrantType());
        paramMap.put("appid", wxConstantConfig.getAppID());
        paramMap.put("secret", wxConstantConfig.getAppSecret());
        log.info("获取accessToken请求参数：{}", JSONObject.toJSONString(paramMap));
        // 发起GET请求获取凭证
        JSONObject jsonObject = JSONObject
                .parseObject(HttpUtil.get(wxConstantConfig.getAccessTokenUrl(), paramMap));
        log.info("获取accessToken响应结果：{}", JSONObject.toJSONString(jsonObject));
        if (ObjectUtil.isNotEmpty(jsonObject)) {
            try {
                accessToken.setAccessToken(jsonObject.getString("access_token"));
                accessToken.setExpiresIn(jsonObject.getIntValue("expires_in"));
                log.info("AccessToken>>>>>>>>>>>>>{}", jsonObject.toString());
            } catch (Exception e) {
                // 获取token失败
                log.error("获取token失败:{}", e.getMessage());
                throw new RuntimeException("获取token失败");
            }
        }
        return accessToken;
    }
}
